let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');

/**
 * 查询功能数据 by p 2018-06-11
 *
 * 按条件查询功能数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];

    sql += (sql === "" ? " where " : " and ") + " type > 0 ";

    if (params.fatherId !== undefined && params.fatherId !== "") {
        sql += (sql === "" ? " where " : " and ") + "fatherId = ? ";
        datas.push(params.fatherId);
    }

    if (params.types !== undefined && params.types !== "") {
        sql += (sql === "" ? " where " : " and ") + "type = ? ";
        datas.push(params.types);
    }



    req.app.db.query("select count(1) as totalCount from menu " + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from menu " + sql + " order by `order` desc" + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});

router.get('/tree', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("SELECT id, name as text, fatherId from menu", [], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }
        let trees = [];
        for (var i = 0; i < results.length; i ++) {
            if (results[i].fatherId === 0) {
                let data = results[i];
                makeTree(results, data);
                trees.push(data);
            }
        }

        res.json({"success": true, "data": trees, "message": ""});
    });
});

function makeTree(r, data) {
    if (r !== undefined) {
        for (var i = 0; i < r.length; i ++) {
            if (data.id  === r[i].fatherId) {
                if (data.nodes === undefined) {
                    data.nodes = [];
                }

                makeTree(r, r[i]);
                data.nodes.push(r[i]);
            }
        }
    }
}

/**
 * 查看功能数据 by p 2018-06-11
 *
 * 按id查看指定的功能信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select * from menu where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

router.get('/:user/tree', filter.authorize, function (req, res, next) {
    let role = req.session.role;

    req.app.db.query("select id, fatherId, type, name, href, `key`, icon, color from menu where FIND_IN_SET(id, (?)) order by `order` desc", [role.power], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "当前用户没有可操作菜单！"});
            return;
        }

        let trees = [];
        for (var i = 0; i < results.length; i ++) {
            if (results[i].fatherId === 0) {
                let data = results[i];
                makeUserMenuTree(results, data);
                trees.push(data);
            }
        }
        res.json({"success": true, "data": trees, "message": ""});
    });
});

router.get('/:user/menus', filter.authorize, function (req, res, next) {
    let role = req.session.role;

    req.app.db.query("select id, fatherId, type, name, href, `key`, icon, color from menu where FIND_IN_SET(id, (?)) order by `order` desc", [role.power], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "当前用户没有可操作菜单！"});
            return;
        }

        let trees = [];
        for (var i = 0; i < results.length; i ++) {
            if (results[i].type === 1) {
                let o = {};
                o.id = results[i].id;
                o.fatherId = results[i].fatherId;
                o.type = results[i].type;
                o.href = results[i].href;
                o.name = results[i].key;
                o.title = results[i].name;
                o.icon = results[i].icon
                o.color = results[i].color;
                trees.push(o);
            }
            else {
                trees.push(results[i]);
            }
        }
        res.json({"success": true, "data": trees, "message": ""});
    });
});

function makeUserMenuTree(r, data) {
    if (r !== undefined) {
        for (var i = 0; i < r.length; i ++) {
            if (r[i].fatherId === data.id) {
                if (data.nodes === undefined) {
                    data.nodes = [];
                }

                makeUserMenuTree(r, r[i]);
                if (r[i].type === 1) {
                    let o = {};
                    o.id = r[i].id;
                    o.fatherId = r[i].fatherId;
                    o.type = r[i].type;
                    o.href = r[i].href;
                    o.name = r[i].key;
                    o.title = r[i].name;
                    o.icon = r[i].icon
                    o.color = r[i].color;
                    data.nodes.push(o);
                }
                else {
                    data.nodes.push(r[i]);
                }
            }
        }
    }
}

/**
 * 修改功能数据 by p 2018-06-11
 *
 *
 */
router.put('/:id', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let types = 2;
    let order = 0;

    if (params.id === undefined || params.id === '') {
        res.json({"success": false, "message": "功能编码错误！"});
        return;
    }

    if (params.fatherId === undefined || params.fatherId === '' || !(params.fatherId >= 0)) {
        res.json({"success": false, "message": "父功能编码错误！"});
        return;
    }

    if (params.type !== undefined && params.type !== "") {
        types = params.type;
    }

    if (params.name === undefined || params.name === '' ) {
        res.json({"success": false, "message": "菜单名称不能为空！"});
        return;
    }

    if (params.order !== undefined && params.order !== "" && params.order > 0) {
        order = params.order;
    }

    let now = new Date();

    req.app.db.query("select text from dic where type = ? and value = ?", ["菜单", params.type], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "菜单类型错误！"});
            return;
        }

        req.app.db.query("update menu set fatherId = ?, type = ?, typeName = ?, name = ?, href = ?, `key` = ?, icon = ?, color = ?, `order` = ?, userId = ?, userName = ?, updateDate = ? where id = ?", [params.fatherId, types, results[0].text, params.name, params.href, params.key, params.icon, params.color, order, user.id, user.trueName, now, params.id], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": global.putMsg});
        });
    });
});

/**
 * 新增功能数据 by p 2018-06-11
 *
 *
 */
router.post('/', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let order = 0;
    let types = 0;

    if (params.fatherId === undefined || params.fatherId === '' || !(params.fatherId >= 0)) {
        res.json({"success": false, "message": "父功能编码错误！"});
        return;
    }

    if (params.type !== undefined && params.type !== "") {
        types = params.type;
    }

    if (params.name === undefined || params.name === '' ) {
        res.json({"success": false, "message": "菜单名称不能为空！"});
        return;
    }

    if (params.order !== undefined && params.order !== "" && params.order > 0) {
        order = params.order;
    }

    let now = new Date();

    req.app.db.query("select text from dic where type = ? and value = ?", ["菜单", params.type], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "菜单类型错误！"});
            return;
        }

        req.app.db.query("insert into menu(fatherId, type, typeName, name, href, `key`, icon, color, `order`, userId, userName, createDate, updateDate) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [params.fatherId, types, results[0].text, params.name, params.href, params.key, params.icon, params.color, order, user.id, user.trueName, now, now], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": global.postMsg});
        });
    });
});

/**
 * 删除功能信息 by v 2018-06-11
 *
 * 按id删除指定的功能信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query('delete from menu where id = ?', [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.deleteMsg});
    });
});

module.exports = router;